package main

import (
	"errors"
	"fmt"
	"sync"
)

type PortPool struct {
	lock     sync.Mutex
	pool     []int
	basePort int
}

func (p *PortPool) Fill(num int) *PortPool {

	p.lock.Lock()

	last := p.basePort
	poolLen := len(p.pool)

	if poolLen != 0 {
		last = p.pool[poolLen-1]
	}

	for i := 0; i < num; i++ {
		p.pool = append(p.pool, last+i)
	}

	return p
}

func (p *PortPool) getPort(index int) (int, error) {

	if index < 0 || index >= len(p.pool) {
		return 0, errors.New("切片越界")
	}

	return p.pool[index], nil

}

func (p *PortPool) portString(index int) (string, error) {

	port, err := p.getPort(index)

	if err != nil {
		return "", errors.New("切片越界")
	}

	return fmt.Sprintf(":%d", port), nil

}
